package com.focusai.efairy.ui.activity.announce;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Menu;
import android.view.MenuItem;

import com.focusai.efairy.R;
import com.focusai.efairy.model.announce.AnnounceItem;
import com.focusai.efairy.model.manager.CacheManager;
import com.focusai.efairy.model.request.GetAnnounceListRequest;
import com.focusai.efairy.model.response.AnnounceListRespnse;
import com.focusai.efairy.model.user.User;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.announce.AnnounceListAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerViewHolder;
import com.focusai.efairy.ui.adapter.base.RecycleViewDivider;
import com.focusai.efairy.ui.base.SwipeBackTipBaseActivity;
import com.focusai.efairy.utils.ScreenUtil;
import com.mylhyl.crlayout.SwipeRefreshAdapterView;
import com.mylhyl.crlayout.SwipeRefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * 公告列表
 * Created by luo_guangwen on 2017/10/10.
 */

public class AnnounceListActivity extends SwipeBackTipBaseActivity implements SwipeRefreshLayout.OnRefreshListener,
        SwipeRefreshAdapterView.OnListLoadListener {
    private static final int REQUEST_CODE_ADD = 0x11;
    private static final int REQUEST_CODE_DETAIL = 0x12;
    private SwipeRefreshRecyclerView mRefreshRecyclerView;
    private AnnounceListAdapter mAdapter;
    private List<AnnounceItem> mList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_list);
        initView();
        setDefaultValues();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        int userRoleLevel = CacheManager.getUserRoleLevel();
        if (userRoleLevel != User.NORMALUSER && userRoleLevel != User.PROJECTADMIN) {
            MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.send_announce).setTitle(R.string.send_announce);
            MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            Intent intent = new Intent(getContext(), InputAnnounceActivity.class);
//            intent.putExtra(ProjectAddDeviceActivity.KEY_PROJECT_ID, projectId);
            startActivityForResult(intent, REQUEST_CODE_ADD);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView() {
        mRefreshRecyclerView = findView(R.id.swipe_recyce_view);
    }

    @Override
    protected void setDefaultValues() {
        setCenterTitleName("公告");
        mAdapter = new AnnounceListAdapter(getContext());
        mList = new ArrayList<>();
        mRefreshRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRefreshRecyclerView.setAdapter(mAdapter);
        mRefreshRecyclerView.getScrollView().addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.VERTICAL, ScreenUtil.dp2pix(15), getResources().getColor(R.color.main_line_gray)));
        mAdapter.refreshData(mList);
        mRefreshRecyclerView.setOnListLoadListener(this);
        mRefreshRecyclerView.setOnRefreshListener(this);
        mRefreshRecyclerView.setRefreshing(true);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerViewHolder holder) {
                int position = mRefreshRecyclerView.getScrollView().getChildLayoutPosition(holder.itemView);
                AnnounceItem item = mList.get(position);
                Intent intent = new Intent(getContext(), AnnounceDetailActivity.class);
                intent.putExtra(AnnounceDetailActivity.KEY_ANNOUNCE_ITEM, item);
                startActivityForResult(intent, REQUEST_CODE_DETAIL);
            }
        });
    }

    @Override
    public void onRefresh() {
        refresh();
    }

    @Override
    public void onListLoad() {
        loadMore();
    }

    private void refresh() {
        HttpManager.getInstance().sendRequest(new GetAnnounceListRequest(0, "",
                new Response.Listener<AnnounceListRespnse>() {
                    @Override
                    protected void onSuccess(AnnounceListRespnse response) {
                        if (response != null && response.announcement_list != null) {
                            mList.clear();
                            mList.addAll(response.announcement_list);
                            mAdapter.notifyDataSetChanged();
                            if (GetAnnounceListRequest.size > mList.size()) {
                                mRefreshRecyclerView.setEnabledLoad(false);
                            } else {
                                mRefreshRecyclerView.setEnabledLoad(true);
                            }
                        }
                        mRefreshRecyclerView.setRefreshing(false);
                        showTip(mList);
                    }

                    @Override
                    protected void onFail(NetworkException exception) {
                        doException(exception);
                        mRefreshRecyclerView.setRefreshing(false);
                        showTip(mList);
                    }
                }));
    }

    private void loadMore() {
        if (mList.size() == 0) {
            mRefreshRecyclerView.setLoading(false);
            return;
        }
        HttpManager.getInstance().sendRequest(new GetAnnounceListRequest(mList.get(mList.size() - 1).efairyannouncement_id, "",
                new Response.Listener<AnnounceListRespnse>() {
                    @Override
                    protected void onSuccess(AnnounceListRespnse response) {
                        if (response != null && response.announcement_list != null) {

                            mList.addAll(response.announcement_list);
                            mAdapter.notifyDataSetChanged();
                            if (mList.size() == response.total_rows) {
                                mRefreshRecyclerView.setEnabledLoad(false);
                            } else {
                                mRefreshRecyclerView.setEnabledLoad(true);
                            }
                        }
                        mRefreshRecyclerView.setLoading(false);
                    }

                    @Override
                    protected void onFail(NetworkException exception) {
                        doException(exception);
                        mRefreshRecyclerView.setLoading(false);
                    }
                }));
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ADD:
                case REQUEST_CODE_DETAIL:
                    if (data != null && data.getBooleanExtra(AnnounceDetailActivity.KEY_ANNOUNCE_READ, false)) {
                        int position = data.getIntExtra(AnnounceDetailActivity.KEY_ANNOUNCE_POSITION, -1);
                        if (position != -1 && position < mList.size()) {
                            mList.get(position).efairyuserhasannouncement_is_read = AnnounceItem.IS_READ;
                            mAdapter.notifyDataSetChanged();
                            return;
                        }
                    }
                    mRefreshRecyclerView.setRefreshing(true);
                    setResult(RESULT_OK);
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
